/*=============================================================================
// File Name: 
// Author:  Wood.Wang
// Date:
// Message:
// Copyright 2022,All right is reserved;
=============================================================================*/
/* Includes -----------------------------------------------------------------*/
#include "drv_adxl345.h"


#define     I2C_NUM     0

void ADXL345_Single_Write(uint8_t REG_Address, uint8_t REG_data)
{
    I2C_WriteByte(I2C_NUM,ADXL345_ADDRESS,REG_Address,REG_data);
}

uint8_t ADXL345_Single_Read(uint8_t REG_Address)
{  
    uint8_t REG_data;
    REG_data = I2C_ReadByte(I2C_NUM,ADXL345_ADDRESS,REG_Address);
    return REG_data; 
}

int ADXL345_GetX(void)
{
    uint8_t x[2]={0};
    I2C_PageRead(I2C_NUM,ADXL345_ADDRESS,ADXL345_REG_DATAX0,x,2);
    return ((int)x[0]|(x[1]<<8));
}

int ADXL345_GetY(void)
{
    uint8_t y[2]={0};
    I2C_PageRead(I2C_NUM,ADXL345_ADDRESS,ADXL345_REG_DATAY0,y,2);
    return ((int)y[0]|(y[1]<<8));
}

int ADXL345_GetZ(void)
{
    uint8_t z[2]={0};
    I2C_PageRead(I2C_NUM,ADXL345_ADDRESS,ADXL345_REG_DATAZ0,z,2);
    return ((int)z[0]|(z[1]<<8));
}

void  ADXL345_GetXYZ(int  *x,int *y,int  *z)
{
    uint8_t xyz[6]={0};
    I2C_PageRead(I2C_NUM,ADXL345_ADDRESS,ADXL345_REG_DATAX0,xyz,6);  
    if(x != NULL)   *x = (int16_t)(xyz[0]|(xyz[1]<<8));
    if(y != NULL)   *y = (int16_t)(xyz[2]|(xyz[3]<<8));
    if(z != NULL)   *z = (int16_t)(xyz[4]|(xyz[5]<<8));
    
}

uint8_t ADXL345_Init(void)
{
    /* Check connection */
    uint8_t deviceid = ADXL345_Single_Read(ADXL345_REG_DEVID);   //0xe5 = id
    if (deviceid != 0xE5)
    {
        /* No ADXL345 detected ... return false */
        return  deviceid;
    }

    // Enable measurements
    ADXL345_Single_Write(ADXL345_REG_DATA_FORMAT,0x09);   //+-4g range

    ADXL345_Single_Write(ADXL345_REG_BW_RATE,0x08);   //
    ADXL345_Single_Write(ADXL345_REG_POWER_CTL,0x08);   //
    ADXL345_Single_Write(ADXL345_REG_INT_ENABLE,0x80);   //

    ADXL345_Single_Write(ADXL345_REG_OFSX,0x00);   //
    ADXL345_Single_Write(ADXL345_REG_OFSY,0x00);   //
    ADXL345_Single_Write(ADXL345_REG_OFSZ,0x00);   //

    return deviceid;
}

void ADXL345_power_down(void)
{
   ADXL345_Single_Write(ADXL345_REG_BW_RATE,0x00);   //
   ADXL345_Single_Write(ADXL345_REG_POWER_CTL,0x00);   //
   ADXL345_Single_Write(ADXL345_REG_INT_ENABLE,0x00);   // 
}


#if UART_SHELL == NR_MICRO_SHELL
#include "nr_micro_shell.h"

void adxl345_read(char argc, char *argv)
{
    int    x,y,z;
    
    printf("ADXL345:%02X\r\n",ADXL345_Init());
    ADXL345_GetXYZ(&x, &y, &z);
    printf("x=%d,\t y=%d, \t z=%d.\r\n",x,y,z);
}

NR_SHELL_CMD_EXPORT(adxl345,   adxl345_read,     "get 3 Axial senser adxl345 data");

#endif

